import hashlib

from fastapi import FastAPI, Query, Path, Body, APIRouter, Request  # Query校验
from pydantic import BaseModel, Field  # --docs 能看到接口信息,  数据验证
from fastapi.middleware.cors import CORSMiddleware  # 跨域
from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory='./')
app = FastAPI(
    title='测试接口',
    verssion='1.0',
    description='接口介绍 在这里'
)
app.add_middleware(CORSMiddleware,
                   allow_origins='*',
                   a1low_credentials=True,
                   a11ow_methods=["*"],
                   a11ow_headers=["*"],
                   )


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


class LoginUser(BaseModel):
    phone: str
    code: str
    nick_name: str = Field(..., max_length=20, pattern=r'[\u4e00-\u9fa5]', title='中文的昵称')


@app.post("/login")
async def user_login(user: LoginUser):
    return {'msg': '登录成功', 'phone': user.phone, 'code': user.code}


@app.post("/login2")
async def user_login2(
        name: str = Query(..., min_length=8, max_length=20, pattern=r'[a-zA-Z]'),
        pwd: str = Query(..., min_length=8, max_length=20, pattern=r'[a-zA-Z]')
):
    return {
        'msg': '登录成功',
        'name': name,
        'pwd': hashlib.sha1(pwd.encode('utf8')).hexdigest()  # 加密验证密码
    }


@app.get('/home')
async def home():
    return templates.TemplateResponse('home.html' )
